#include <stdlib.h>
#include "CIpodProtocol.h"

CIpodProtocol::CIpodProtocol() {
    pthread_mutex_init(&m_queueMutex, NULL);
    pthread_cond_init(&m_queueCond, NULL);
    m_threadRunning = true;
    
    // 创建发送线程
    pthread_create(&m_sendThread, NULL, sendThreadFunc, this);

}

CIpodProtocol::~CIpodProtocol() {
    // 停止发送线程
    pthread_mutex_lock(&m_queueMutex);
    m_threadRunning = false;
    pthread_cond_signal(&m_queueCond);
    pthread_mutex_unlock(&m_queueMutex);
    
    pthread_join(m_sendThread, NULL);
    
    // 清理队列中的数据
    while (!m_sendQueue.empty()) {
        delete[] m_sendQueue.front().data;
        m_sendQueue.pop();
    }
    
    pthread_mutex_destroy(&m_queueMutex);
    pthread_cond_destroy(&m_queueCond);

    m_Proxy = NULL;
}

void CIpodProtocol::registerProxy(CIpodProxy *proxy) {
    m_Proxy = proxy;
}

void CIpodProtocol::unregisterProxy() {
}

ipod_t CIpodProtocol::getHandle() {
    if (m_Proxy != NULL) {
        return m_Proxy->getHandle();
    }
    return -1;
}

//int CIpodProtocol::send(const uint8 *data, uint16 len, bool native) {
//    if (m_Proxy != NULL) {
//        return m_Proxy->send(data, len, native);
//    }
//    return -1;
//}


void* CIpodProtocol::sendThreadFunc(void* arg) {
    CIpodProtocol* protocol = static_cast<CIpodProtocol*>(arg);
    protocol->processSendQueue();
    return NULL;
}

void CIpodProtocol::processSendQueue() {
    while (true) {
        pthread_mutex_lock(&m_queueMutex);
        
        while (m_sendQueue.empty() && m_threadRunning) {
            pthread_cond_wait(&m_queueCond, &m_queueMutex);
        }
        
        if (!m_threadRunning && m_sendQueue.empty()) {
            pthread_mutex_unlock(&m_queueMutex);
            break;
        }
        
        // 获取队列中的数据
        SendData sendData = m_sendQueue.front();
        m_sendQueue.pop();
        
        pthread_mutex_unlock(&m_queueMutex);
        
        // 执行发送操作
        if (m_Proxy != NULL) {
            m_Proxy->send(sendData.data, sendData.len, sendData.native);
        }
        
        // 清理数据
        delete[] sendData.data;
    }
}

int CIpodProtocol::send(const uint8 *data, uint16 len, bool native) {
    if (m_Proxy == NULL) {
        return -1;
    }
    
    // 复制数据
    uint8* dataCopy = new uint8[len];
    memcpy(dataCopy, data, len);
    
    // 创建发送数据结构
    SendData sendData{dataCopy, len, native};
    
    // 添加到发送队列
    pthread_mutex_lock(&m_queueMutex);
    m_sendQueue.push(sendData);
    pthread_cond_signal(&m_queueCond);
    pthread_mutex_unlock(&m_queueMutex);
    
    return 0;
}

bool CIpodProtocol::isDeviceExist() {
    if (m_Proxy != NULL) {
        return m_Proxy->isDeviceExist();
    }
    return false;
}

bool CIpodProtocol::isExiting() {
    if (m_Proxy != NULL) {
        return m_Proxy->isExiting();
    }
    return true;
}
